package util;


import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Created by CHENCO7 on 7/20/2017.
 */
public class JsonUtil {
    public static Object toJsonObject(String jsonString, Class clazz){
        ObjectMapper mapper = new ObjectMapper();
        Object obj = null;
        try {
            obj = mapper.readValue(jsonString, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static String toJsonString(Object object){
        ObjectMapper mapper = new ObjectMapper();
        String result = null;
        try {
            result = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static Object toJsonListObject(String jsonString,Class<?> collectionClass, Class<?>... elementClasses){
   	 ObjectMapper mapper = new ObjectMapper();
	     Object obj = null;
	     try {
			obj = mapper.readValue(jsonString, getCollectionType(mapper, collectionClass, elementClasses));
		} catch (JsonParseException e) {
			System.out.println("connect error.....");
//			e.printStackTrace();
		} catch (JsonMappingException e) {
//			e.printStackTrace();
		} catch (IOException e) {
//			e.printStackTrace();
		}
	     return obj;
   }
   
   
   
   public static JavaType getCollectionType(ObjectMapper mapper,Class<?> collectionClass, Class<?>... elementClasses) {     
       return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);     
   }  
}
